﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Consul;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using User.API.Data;
using User.API.Models;

namespace User.API
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var myConn = Configuration.GetConnectionString("default");
            services.AddDbContext<UserContext>(opt => opt.UseMySQL(myConn));
            services.AddMvc();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(opt =>
                {
                    opt.Audience = "user_api";
                    opt.RequireHttpsMetadata = false;
                    opt.SaveToken = true;
                    opt.Authority = "http://localhost:8002";
                });

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            var options = new ServiceDiscoveryOptions();
            Configuration.Bind("ServiceDiscovery", options);
            //var consul = new ConsulClient(cfg => cfg.Address = new Uri(options.Consul.HttpEndpoint));
            var consul = new ConsulClient();
            var serviceRegistration = new AgentServiceRegistration()
            {
                Address = options.Service.Address,
                ID = $"userapi_{options.Service.Address}:{options.Service.Port}",
                Name = options.Service.Name,
                Port = options.Service.Port,
                Check = new AgentServiceCheck()
                {
                    Interval = TimeSpan.FromSeconds(3),
                    DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(20),
                    HTTP = $"{options.Service.GetUrl()}/api/HealthCheck/Ping"
                }
            };
            lifetime.ApplicationStarted.Register(() =>
            {
                consul.Agent.ServiceRegister(serviceRegistration).ConfigureAwait(false);
            });
            lifetime.ApplicationStopped.Register(() =>
            {
                consul.Agent.ServiceDeregister(serviceRegistration.ID).ConfigureAwait(false);
            });
            app.UseMvc();
            app.UseAuthentication();
        }
    }
}
